<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Promise入门简介及相关使用.md |  Small Bridge
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/css/main.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

<link rel="alternate" href="/atom.xml" title="Small Bridge" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-Promise入门简介及相关使用-md" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Promise入门简介及相关使用.md
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/09/07/Promise%E5%85%A5%E9%97%A8%E7%AE%80%E4%BB%8B%E5%8F%8A%E7%9B%B8%E5%85%B3%E4%BD%BF%E7%94%A8-md/" class="article-date">
  <time datetime="2020-09-07T13:33:45.000Z" itemprop="datePublished">2020-09-07</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript/">JavaScript</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.6k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">11分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    
    <div class="article-entry" itemprop="articleBody">
      


      

      
      <p>@<a href="Promise">TOC</a></p>
<h1 id="引入"><a href="#引入" class="headerlink" title="引入"></a>引入</h1><a id="more"></a>
<p>在真正开始了解Promise之前，我先提一下有关问题，为后续的讲解做好铺垫</p>
<ol>
<li><p>实例对象与函数对象<br>函数对象：将函数作为对象使用时，简称为函数对象<br>实例对象：new函数产生的对象，简称为对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    函数对象：将函数作为对象使用时，简称为函数对象</span></span><br><span class="line"><span class="comment">    实例对象：new函数产生的对象，简称为对象</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">Fn</span>(<span class="params"></span>)</span>&#123;  <span class="comment">//Fn函数</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> fn = <span class="keyword">new</span> Fn() <span class="comment">//Fn是构造函数 fn是实例对象(简称为对象)</span></span><br><span class="line">    <span class="built_in">console</span>.log(Fn.prototype) <span class="comment">//Fn是函数对象</span></span><br><span class="line">    Fn.call(&#123;&#125;)  <span class="comment">//Fn是函数对象</span></span><br><span class="line">    $(<span class="string">'#test'</span>)  <span class="comment">//jQuery函数</span></span><br><span class="line">    $.<span class="keyword">get</span>('/<span class="keyword">get</span>') //jQuery函数对象</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>两种类型的回调函数<br>同步回调：立即执行，完全执行完了才结束，不会放入到回调队列中，比如数组遍历相关的回调函数，Promise的executor执行器函数<br>异步回调：不会立即执行，会放入到回调队列中将来执行，比如定时器回调，ajax回调，Promise成功/失败的回调</p>
</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    1).同步回调：</span></span><br><span class="line"><span class="comment">    理解：立即执行，完全执行完了才结束，不会放入回调队列中</span></span><br><span class="line"><span class="comment">    例子：数组遍历相关的回调函数 / Promise的excutor函数</span></span><br><span class="line"><span class="comment">    2).异步回调：</span></span><br><span class="line"><span class="comment">    理解：不会立即执行，会放入回调队列中将来执行</span></span><br><span class="line"><span class="comment">    例子：定时器回调 / ajax回调 / Promise的成功|失败的回调</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//同步回调</span></span><br><span class="line">    <span class="keyword">let</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]</span><br><span class="line">    arr.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(item);</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"forEach之后"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//异步回调</span></span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"setTimeout"</span>);</span><br><span class="line">    &#125;, <span class="number">0</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"setTimeout之后"</span>);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li>JS的错误<br>错误的类型<br>Error：所有错误的父类型<br>ReferenceError：引用的变量不存在<br>TypeError：数据类型不正确的错误<br>RangeError：数据值不在其所允许的范围内<br>SyntaxError：语法错误<br>错误处理<br>捕获错误：try…catch<br>抛出错误：throw Error<br>错误对象<br>message属性：错误相关信息<br>stack属性：函数调用栈记录信息 </li>
</ol>
<p>在有了这些引入之后，我将从三个方面介绍Promise：<br>Promise是什么？<br>为什么要使用Promise？<br>怎么使用Promise？</p>
<h1 id="What"><a href="#What" class="headerlink" title="What"></a>What</h1><ol>
<li><p>Promise是什么？<br>抽象表达：Promise是JS中进行异步编程的新的解决方案(旧的是纯回调的形式)<br>具体表达<br>从语法上来说：Promise就是一个构造函数<br>从功能上来说：Promise对象用于封装一个异步操作并可以获取其结果</p>
</li>
<li><p>Promise的状态改变<br>pending变为resolved<br>pending变为rejected<br>只有这两种，且一个Promise对象只能改变一次，无论变为成功还是失败，都会有一个结果数据，成功的数据一般称为value，失败的数据一般称为reason</p>
</li>
<li><p>Promise的基本流程<br><img src="https://img-blog.csdnimg.cn/20200824230121613.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NjI1MTQy,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
</li>
<li><p>Promise的基本使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//1.创建一个新的Promise对象</span></span><br><span class="line">    <span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123; <span class="comment">//执行器函数 同步回调</span></span><br><span class="line">       <span class="built_in">console</span>.log(<span class="string">"执行 excutor"</span>);</span><br><span class="line">        <span class="comment">//2.执行异步任务</span></span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">const</span> time = <span class="built_in">Date</span>.now()</span><br><span class="line">            <span class="keyword">if</span> (time % <span class="number">2</span> === <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">//3.1如果成功，执行resolve(value)</span></span><br><span class="line">                resolve(<span class="string">'成功的数据,time='</span> + time)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//3.2如果失败，执行reject(reason)</span></span><br><span class="line">                reject(<span class="string">'失败的数据,time='</span> + time)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"new Promise 之后"</span>);</span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        p.then(</span><br><span class="line">        value =&gt; &#123; <span class="comment">//接收得到成功的value数据  onResolved</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'成功的回调'</span> + value);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123; <span class="comment">//接收得到失败的reason数据  onRejected</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'失败的回调'</span> + reason);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">    &#125;, <span class="number">2000</span>);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h1 id="Why"><a href="#Why" class="headerlink" title="Why"></a>Why</h1><ol>
<li><p>指定回调函数的方式更加灵活<br>旧的：必须在启动异步任务前指定<br>Promise：启动异步任务===》返回Promise对象===》给Promise对象绑定回调函数<br>甚至可以在异步任务结束后指定多个</p>
</li>
<li><p>支持链式调用，可以解决回调地狱问题<br>什么是回调地狱？<br>回调函数嵌套调用，外部回调函数异步执行的结果是嵌套的回调执行的条件，使得书写呈现一个开口向左的V形，这样不便于阅读，也不便于异常处理，这就可以使用Promise链式调用解决，或者使用更好的解决方案async/await</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 成功的回调函数</span></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">successCallback</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">       <span class="built_in">console</span>.log(<span class="string">"声音文件创建成功: "</span> + result);</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="comment">// 失败的回调函数</span></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">failureCallback</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">       <span class="built_in">console</span>.log(<span class="string">"声音文件创建失败: "</span> + error);</span><br><span class="line">     &#125;</span><br><span class="line">   </span><br><span class="line">     <span class="comment">/* 1.1 使用纯回调函数 */</span></span><br><span class="line">     createAudioFileAsync(audioSettings, successCallback, failureCallback)</span><br><span class="line">     </span><br><span class="line">   <span class="comment">/* 1.2. 使用Promise */</span></span><br><span class="line">     <span class="keyword">const</span> promise = createAudioFileAsync(audioSettings); <span class="comment">// 2</span></span><br><span class="line">     setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">       promise.then(successCallback, failureCallback);</span><br><span class="line">     &#125;, <span class="number">3000</span>);</span><br><span class="line">     </span><br><span class="line">     <span class="comment">/* </span></span><br><span class="line"><span class="comment">     2.1. 回调地狱</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">     doSomething(<span class="function"><span class="keyword">function</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">       doSomethingElse(result, <span class="function"><span class="keyword">function</span>(<span class="params">newResult</span>) </span>&#123;</span><br><span class="line">         doThirdThing(newResult, <span class="function"><span class="keyword">function</span>(<span class="params">finalResult</span>) </span>&#123;</span><br><span class="line">           <span class="built_in">console</span>.log(<span class="string">'Got the final result: '</span> + finalResult)</span><br><span class="line">         &#125;, failureCallback)</span><br><span class="line">       &#125;, failureCallback)</span><br><span class="line">     &#125;, failureCallback)</span><br><span class="line">   </span><br><span class="line">     <span class="comment">/* </span></span><br><span class="line"><span class="comment">     2.2. 使用promise的链式调用解决回调地狱</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">     doSomething()</span><br><span class="line">     .then(<span class="function"><span class="keyword">function</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">       <span class="keyword">return</span> doSomethingElse(result)</span><br><span class="line">     &#125;)</span><br><span class="line">     .then(<span class="function"><span class="keyword">function</span>(<span class="params">newResult</span>) </span>&#123;</span><br><span class="line">       <span class="keyword">return</span> doThirdThing(newResult)</span><br><span class="line">     &#125;)</span><br><span class="line">     .then(<span class="function"><span class="keyword">function</span>(<span class="params">finalResult</span>) </span>&#123;</span><br><span class="line">       <span class="built_in">console</span>.log(<span class="string">'Got the final result: '</span> + finalResult)</span><br><span class="line">     &#125;)</span><br><span class="line">     .catch(failureCallback)</span><br><span class="line">   </span><br><span class="line">     <span class="comment">/* </span></span><br><span class="line"><span class="comment">     2.3. async/await: 回调地狱的终极解决方案</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">     <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="keyword">const</span> result = <span class="keyword">await</span> doSomething()</span><br><span class="line">         <span class="keyword">const</span> newResult = <span class="keyword">await</span> doSomethingElse(result)</span><br><span class="line">         <span class="keyword">const</span> finalResult = <span class="keyword">await</span> doThirdThing(newResult)</span><br><span class="line">         <span class="built_in">console</span>.log(<span class="string">'Got the final result: '</span> + finalResult)</span><br><span class="line">       &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">         failureCallback(error)</span><br><span class="line">       &#125;</span><br><span class="line">     &#125;</span><br></pre></td></tr></table></figure>
<h1 id="How"><a href="#How" class="headerlink" title="How"></a>How</h1></li>
<li><p>API</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">//resolve('成功的数据')</span></span><br><span class="line">            reject(<span class="string">'失败的数据'</span>)</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onResolved()1"</span>,value);</span><br><span class="line">        &#125;</span><br><span class="line">    ).catch(</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onRejected()1"</span>,reason);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="comment">//产生一个成功值为1的Promise对象</span></span><br><span class="line">    <span class="keyword">const</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">        resolve(<span class="number">1</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">const</span> p2 = <span class="built_in">Promise</span>.resolve(<span class="number">2</span>)</span><br><span class="line">    <span class="keyword">const</span> p3 = <span class="built_in">Promise</span>.reject(<span class="number">3</span>)</span><br><span class="line">    p1.then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;<span class="built_in">console</span>.log(value);&#125;)</span><br><span class="line">    p2.then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;<span class="built_in">console</span>.log(value);&#125;)</span><br><span class="line">    p3.catch(<span class="function"><span class="params">reason</span> =&gt;</span> &#123;<span class="built_in">console</span>.log(reason);&#125;)</span><br><span class="line">     </span><br><span class="line">     <span class="comment">//都成功才成功，否则失败</span></span><br><span class="line">    <span class="comment">//const pAll = Promise.all([p1,p2,p3]) //失败</span></span><br><span class="line">    <span class="keyword">const</span> pAll = <span class="built_in">Promise</span>.all([p1,p2])  <span class="comment">//成功返回数组，数据顺序与执行的顺序无关，跟数组中的顺序完全一致</span></span><br><span class="line">    pAll.then(</span><br><span class="line">        values =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"all onResolved()"</span>,values);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"all onRejected()"</span>,reason);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">     </span><br><span class="line">     <span class="comment">//返回第一个完成的Promise对象的结果</span></span><br><span class="line">    <span class="comment">//const pRace = Promise.race([p1,p2,p3])   //成功</span></span><br><span class="line">    <span class="keyword">const</span> pRace = <span class="built_in">Promise</span>.race([p3,p1,p2])  <span class="comment">//失败</span></span><br><span class="line">    pRace.then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"race onResolved()"</span>,value);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"race onRejected()"</span>,reason);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Promise的几个关键问题<br>如何改变Promise的状态？<br>（1）resolve(value)  当前是pending，由pending变为resolved<br>（2）reject(reason)  当前是pending，由pending变为rejected<br>（3）抛出异常  当前是pending，由pending变为rejected<br>一个promise指定多个回调函数，都会执行吗？<br>当promise变为对应状态的时候都会执行</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">   <span class="keyword">const</span> p  = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">       <span class="comment">//resolve('成功')  //改变状态pending为resolved</span></span><br><span class="line">       <span class="comment">//reject('失败')   //改变状态pending为rejected</span></span><br><span class="line">       <span class="comment">//throw new Error('出错了') //rejected reason为抛出的错误</span></span><br><span class="line">       <span class="keyword">throw</span> <span class="number">3</span>    <span class="comment">//reason 为3</span></span><br><span class="line">   &#125;)</span><br><span class="line">   </span><br><span class="line">   p.then(</span><br><span class="line">       value =&gt; &#123;</span><br><span class="line">           <span class="built_in">console</span>.log(value);</span><br><span class="line">       &#125;,</span><br><span class="line">       reason =&gt; &#123;</span><br><span class="line">           <span class="built_in">console</span>.log(<span class="string">'onRejected()1'</span>,reason);</span><br><span class="line">       &#125;</span><br><span class="line">   )</span><br><span class="line">   p.then(</span><br><span class="line">    value =&gt; &#123;</span><br><span class="line">           <span class="built_in">console</span>.log(value);</span><br><span class="line">       &#125;,</span><br><span class="line">       reason =&gt; &#123;</span><br><span class="line">           <span class="built_in">console</span>.log(<span class="string">'onRejected()2'</span>,reason);</span><br><span class="line">       &#125;</span><br><span class="line">   )</span><br><span class="line">   <span class="comment">//多个回调都会执行</span></span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>改变promise状态和指定回调函数谁先谁后？<br>（1）都可能，正常情况下是先指定回调再改变状态，但也可以先改变状态后指定回调<br>（2）如何先改变状态后指定回调？<br>    在执行器中直接调用resolve()/reject()<br>    延时之后才调用then()<br>（3）什么时候得到数据？<br>  如果先指定的回调，那当状态发生改变时，回调函数就会调用，得到数据<br>  如果先改变的状态，那当指定回调时，回调函数就会调用，得到数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//常规</span></span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            resolve(<span class="string">'成功'</span>) <span class="comment">//后改变状态，异步执行回调函数</span></span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;).then(</span><br><span class="line">        value =&gt; &#123; <span class="comment">//先指定回调，保存回调函数</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'value1'</span>,value);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'reason1'</span>,reason);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">        resolve(<span class="string">'成功'</span>) <span class="comment">//先改变状态</span></span><br><span class="line">    &#125;).then(</span><br><span class="line">        value =&gt; &#123; <span class="comment">//后指定回调，异步执行回调函数</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'value2'</span>,value);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'reason2'</span>,reason);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            resolve(<span class="string">'成功'</span>) <span class="comment">//先改变状态</span></span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">    p.then(</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">           value =&gt; &#123; <span class="comment">//后指定回调，异步执行回调函数</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'value3'</span>,value);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'reason3'</span>,reason);</span><br><span class="line">        &#125;  </span><br><span class="line">        &#125;, <span class="number">1100</span>)</span><br><span class="line">    )</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

<p>promise.then()返回的新的promise的结果状态由什么决定？<br>（1）简单表达：由then()指定的回调函数执行的结果决定<br>（2）详细表达<br> 如果抛出异常，新promise变为rejected，reason为抛出的异常<br> 如果返回的是非promise的任意值，新promise变为resolved，value为返回的值，不写默认就是return dundefined<br> 如果返回的是另一个新的promise，此promise的结果就会变成新promise的结果</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">        resolve(<span class="number">1</span>)</span><br><span class="line">        <span class="comment">//reject(1)</span></span><br><span class="line">    &#125;).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onResolved()1"</span>,value); <span class="comment">//这样写相当于return undefined</span></span><br><span class="line">            <span class="comment">//return 1</span></span><br><span class="line">            <span class="comment">//return Promise.resolve(2)</span></span><br><span class="line">            <span class="comment">//return Promise.reject(3)</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="number">4</span></span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onRejected()1"</span>,reason);</span><br><span class="line">        &#125;</span><br><span class="line">    ).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onResolved()2"</span>,value);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onRejected()2"</span>,reason);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">    <span class="comment">//.then()返回的新promise的结果状态由then()指定的回调函数执行的结果决定</span></span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

<p> Promise如何串联多个操作任务？<br> promise的then()返回一个新的promise，可以形成then()的链式调用<br> 通过这样的方式串联多个操作(同步/异步)任务</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//串联多个操作任务(同步/异步均可以串联)</span></span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"执行任务1(异步)"</span>);</span><br><span class="line">            resolve(<span class="number">1</span>)</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"任务1的结果:"</span>, value);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"执行任务2(同步)"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="number">2</span></span><br><span class="line">        &#125;,</span><br><span class="line">    ).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"任务2的结果:"</span>, value);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"执行任务3(异步)"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">                setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">                    resolve(<span class="number">3</span>)</span><br><span class="line">                &#125;, <span class="number">1000</span>);</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    ).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"任务3的结果:"</span>, value);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

<p>Promise异常传透<br>当使用promise的链式调用时，可以在最后指定失败的回调，前面任何操作出现异常，最后都会传递到失败的回调中执行处理<br>中断Promise链<br>当使用promise的链式调用的时候，在中间中断，不再执行后面的回调函数，我们可以使用在中断的地方返回一个pending状态的Promise对象<br>return new Promise(() =&gt; {})</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">//resolve(1)</span></span><br><span class="line">        reject(<span class="number">1</span>) <span class="comment">//异常传透</span></span><br><span class="line">    &#125;).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onResolved1()"</span>, value);</span><br><span class="line">        &#125;</span><br><span class="line">    ).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onResolved2()"</span>, value);</span><br><span class="line">        &#125;</span><br><span class="line">    ).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"onResolved3()"</span>, value);</span><br><span class="line">        &#125;</span><br><span class="line">    ).catch(</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'onRejectd()'</span>, reason)</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">()</span> =&gt;</span> &#123;&#125;) <span class="comment">//pending状态的Promise中断链条</span></span><br><span class="line">        &#125;</span><br><span class="line">    ).then(</span><br><span class="line">        value =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"成功"</span>);</span><br><span class="line">        &#125;,</span><br><span class="line">        reason =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"失败"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>有点多了，下期为大家带来自定义Promise</p>

      
      <!-- reward -->
      
      <div id="reward-btn">
        打赏
      </div>
      
    </div>
    
    
      <!-- copyright -->
      
        <div class="declare">
          <ul class="post-copyright">
            <li>
              <i class="ri-copyright-line"></i>
              <strong>版权声明： </strong s>
              本博客所有文章除特别声明外，均采用 <a href="https://www.apache.org/licenses/LICENSE-2.0.html" rel="external nofollow"
                target="_blank">Apache License 2.0</a> 许可协议。转载请注明出处！
            </li>
          </ul>
        </div>
        
    <footer class="article-footer">
      
          
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://lockme.gitee.io/2020/09/07/Promise%E5%85%A5%E9%97%A8%E7%AE%80%E4%BB%8B%E5%8F%8A%E7%9B%B8%E5%85%B3%E4%BD%BF%E7%94%A8-md/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Node-js/" rel="tag">Node.js</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Promise/" rel="tag">Promise</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%8A%80%E6%9C%AF/" rel="tag">技术</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/09/07/%E8%87%AA%E5%AE%9A%E4%B9%89Promise-md/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            自定义Promise.md
          
        </div>
      </a>
    
    
      <a href="/2020/09/07/axios%E6%8B%A6%E6%88%AA%E5%99%A8%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F%E7%9A%84%E6%BA%90%E7%A0%81%E8%A7%A3%E9%87%8A-md/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">axios拦截器执行顺序的源码解释.md</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        app_id: 'pmaQYnbUE9O0H1hiYKLiec4R-gzGzoHsz',
        app_key: 'LMujtI79W4vgEQ3Az5IMo50y',
        path: window.location.pathname,
        notify: 'false',
        verify: 'false',
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020
        月下ctrlc
      </li>
      <li>
        
        Powered by
        
        
        <a href="https://hexo.io" target="_blank">Hexo</a> Theme <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
    <aside class="sidebar">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/avatar.jpg" alt="Small Bridge"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Vue/">Vue</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://shenyu-vip.lofter.com" target="_blank" rel="noopener">主题作者相册</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2020/03/18/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>拿钱砸死我吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/share.js"></script>


<script src="/js/lazyload.min.js"></script>


<script>
  try {
    var typed = new Typed("#subtitle", {
      strings: ['面朝大海，春暖花开', '愿你一生努力，一生被爱', '想要的都拥有，得不到的都释怀'],
      startDelay: 0,
      typeSpeed: 200,
      loop: true,
      backSpeed: 100,
      showCursor: true
    });
  } catch (err) {
  }

</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>



<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/js/ayer.js"></script>



<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>


<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
  var ayerConfig = {
    mathjax: true
  }
</script>



<script src="/js/busuanzi-2.3.pure.min.js"></script>



<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>


    
  </div>
</body>

</html>